import { ACPublisher } from './ACPublisher';
import { ACSubscriberHolder } from './ACSubscriberHolder';

export class ACSubject<T> {

  protected publisherList: ACPublisher<T>[] = [];

  addPublisher(): ACPublisher<T> {
    let publisher = new ACPublisher<T>();
    this.publisherList.push(publisher);
    return publisher;
  }

  on(callback: (value: T) => void): ACSubscriberHolder {
    return this.addPublisher().subscribeValue(callback);
  }

  sendValue(value: T) {
    let pubList: ACPublisher<T>[] = Array.from(this.publisherList);
    for (let pubRef of pubList) {
      if (pubRef.isValid()) {
        pubRef.sendValue(value);
      } else {
        let index = this.publisherList.indexOf(pubRef);
        this.publisherList.splice(index, 1)
      }
    }
  }

}
